package cn.wolfcode.luowowo.service.impl;

import cn.wolfcode.luowowo.domain.StrategyComment;
import cn.wolfcode.luowowo.repository.StrategyCommentRepository;
import cn.wolfcode.luowowo.service.IStrategyCommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Optional;

@Service
//@Transactional
public class StrategyCommentServiceImpl implements IStrategyCommentService {
    //注入攻略评价仓库接口
    @Autowired
    private StrategyCommentRepository strategyCommentRepository;

    @Override
    public void save(StrategyComment strategyComment) {
        strategyComment.setId(null);
        strategyComment.setCreateTime(new Date());
        strategyCommentRepository.save(strategyComment);
    }

    public StrategyComment get(String id) {
        Optional<StrategyComment> op = strategyCommentRepository.findById(id);
        if (op.isPresent()) {
            return op.get();
        }
        return null;
    }

    //改变点赞状态
    @Override
    public void commentThumb(String cid, String uid) {
        //先判断用户是否已经点赞了，根据点别人的赞集合里是否有当前用户id
        //先获取别人的点赞集合
        StrategyComment strategyComment = this.get(cid);
        List<String> thumbuplist = strategyComment.getThumbuplist();
        //如果别人的点赞集合里有我的id就证明我已经点赞了
        //如果已经点赞了，再点赞，就点赞数减一，将用户从集合中移除
        if (thumbuplist.contains(uid)) {
            strategyComment.setThumbupnum(strategyComment.getThumbupnum() - 1);
            thumbuplist.remove(uid);
            //已经没点赞，再点赞，就点赞数加一，将用户添加到点赞集合中
        } else {
            strategyComment.setThumbupnum(strategyComment.getThumbupnum() + 1);
            thumbuplist.add(uid);
        }
        strategyCommentRepository.save(strategyComment);
    }
}
